package org.gjy.m8.concurrent;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-06-30 16:27:58
 */
public class ConditionGeneric {

    private static final Lock lock = new ReentrantLock(true);
    private static final AtomicInteger STATE = new AtomicInteger(0);
    private final Condition[] conditions;
    private final Integer threadCount;
    private final Integer printTimes;

    public ConditionGeneric(Integer threadCount, Integer printTimes) {
        this.threadCount = threadCount;
        this.conditions = new Condition[threadCount];
        this.printTimes = printTimes;
    }

    public void print(int targetState, String content) {
        lock.lock();
        try {
            for (int i = 0; i < printTimes; i++) {
                while (STATE.get() % threadCount != targetState) {
                    conditions[targetState].await();
                }
            }
            System.out.print(content);
            STATE.incrementAndGet();
            conditions[(targetState + 1) % threadCount].signal();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
}
